package com.tuda.common.utils.file;

import com.aliyun.oss.OSSClient;
import com.tuda.common.utils.DateUtils;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

/**
 * @ClassName OssUploadUtils
 * @Description TODO
 * @Author Admin
 * @Date 2023/7/17 12:06
 * @Version 1.0
 **/
public class OssUploadUtils {

    private final static Logger logger = LoggerFactory.getLogger(OssUploadUtils.class);

    private final static String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    private final static String accessKeyId = "LTAI5t5s3jmCNWhXWk22zrzQ";
    private final static String accessKeySecret = "Yeq1jTUCCvrPO3ZLN7ypCQvAMXmB6l";
    private static String bucketName = "tuda";

    /**
     * 将本地图片转换为base64
     * @param imgPath 图片路径
     * @return
     */
    public static String localImageToBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        String result = Base64.encodeBase64String(data);
        // 返回Base64编码过的字节数组字符串
        return result;
    }

    /**
     * 将网络地址对应的图片转换为base64
     * @param imagePath 图片路径
     * @return
     */
    public static String imageToBase64(String imagePath) {
        if (!imagePath.contains("https")) {
            imagePath = imagePath.replaceAll("http", "https");
        }
        ByteArrayOutputStream outPut = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        try {
            // 创建URL
            URL url = new URL(null, imagePath, new sun.net.www.protocol.https.Handler());
            // 创建链接
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10 * 1000);
            if (conn.getResponseCode() != sun.net.www.protocol.http.HttpURLConnection.HTTP_OK) {
                return "fail";//连接失败/链接失效/图片不存在
            }
            InputStream inStream = conn.getInputStream();
            int len = -1;
            while ((len = inStream.read(data)) != -1) {
                outPut.write(data, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        return Base64.encodeBase64String(outPut.toByteArray());
    }

    /**
     * 判断文件大小
     *
     * @param len  文件长度
     * @param size 限制大小
     * @param unit 限制单位（B,K,M,G）
     * @return
     */
    public static boolean checkFileSize(Long len, int size, String unit) {
        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }

    /**
     * 获取指定文件或文件夹的后缀名
     * @param fileName  文件名称
     * @return
     */
    public static String getFileSuffix(String fileName){
        return fileName.substring(fileName.lastIndexOf("."));//例如：abc.png  截取后：.png
    }

    /**
     * 直接上传
     *
     * @return
     */
    public static String ossUpload(InputStream file) {
        String date = DateUtils.format(new Date(), DateUtils.YYYYMMDD_SIMPLE);
        String dateStr = DateUtils.format(new Date(), DateUtils.YYYYMMDDHHMMSS);
        String pictureName = "img/dateproject/" + date + "/" + UUID.randomUUID() + dateStr + ".png";
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 上传文件流。
        ossClient.putObject(bucketName, pictureName, file);
        // 关闭OSSClient。
        ossClient.shutdown();
        return "https://oss.tudayunshu.cn/" + pictureName;
    }

    /**
     * 上传视频
     * @return
     */
    public String ossUploadVideo(InputStream file) {
        String date = DateUtils.format(new Date(), DateUtils.YYYYMMDD_SIMPLE);
        String dateStr = DateUtils.format(new Date(), DateUtils.YYYYMMDDHHMMSS);
        String videoName = "video/chn/" + date + "/" + UUID.randomUUID() + dateStr + ".mp4";
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 上传文件流。
        ossClient.putObject(bucketName, videoName, file);
        // 关闭OSSClient。
        ossClient.shutdown();
        return "https://oss.tudayunshu.cn/" + videoName;
    }


}
